<template>
  <div class="box1 clear">
    <i class="fa fa-arrow-left" id="left" @click="handClick1()"></i>
    <div class="searchBox clear">
      <i class="fa fa-search"></i>
      <input type="text" v-model="value" />
    </div>
    <button @click="handClick2()">搜索</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      value: this.$store.state.searchVal,
      state: true
    }
  },
  methods: {
    handClick1 () {
      this.$router.push('/')
      this.state = true
    },
    handClick2 () {
      this.$store.state.searchVal = this.value
      if (this.value != '' && this.$route.path != '/list3') {
        this.$router.push('/list3')
      }
      // localStorage.setItem('searchData','{"arr": [1,2,3]}')

      // 搜索记录功能
      const state = localStorage.getItem('searchData')
      const searchData = {
        arr:
          state == null ? [] : JSON.parse(localStorage.getItem('searchData')).arr
      }
      console.log(searchData.arr)

      if (this.value == '') {
        return
      } else {
        if (!searchData.arr.includes(this.value)) {
          searchData.arr.unshift(this.value)
          console.log(searchData.arr)
          localStorage.setItem('searchData', JSON.stringify(searchData))
        }
      };
    }
  },

  watch: {
    value () {
      if (this.state) {
        this.$router.push('/list2')
        this.state = false
      }
      if (this.value == '') {
        this.$router.push({ name: 'list1' })
        this.state = true
      } else {
        fetch(`http://127.0.0.1/search?name=${this.value}`)
          .then((res) => res.json())
          .then((res) => {
            this.$bus.$emit('search', res)
          })
      }
    }
  }
}
</script>

<style scoped>
.box1 {
  width: 100%;
  position: fixed;
  top: 0;
  background-color: white;
  z-index: 99;
}
.box1 #left {
  width: 2.5rem;
  line-height: 2rem;
  text-align: center;
  font-size: 16px;
  float: left;
  margin-left: 10px;
  margin: 0.5rem auto;
}
.searchBox {
  width: 18rem;
  background-color: #f5f5f5;
  margin: 0.5rem auto;
  border-radius: 15px;
  float: left;
}
.searchBox i {
  margin-left: 10px;
}
.searchBox input {
  height: 2rem;
  padding-left: 10px;
  background-color: #f5f5f5;
  border: none;
  outline: none;
}
.box1 button {
  width: 2rem;
  line-height: 2rem;
  float: right;
  margin: 0.5rem 0.5rem 0 0;
  border: 0;
  background: none;
  font-size: 16px;
  font-weight: 700;
  color: black;
}
</style>
